<?php
/*
 * cui:phpstorm
 * 2021/7/24
 * 16:52
 * User: s1mple_qcloud@163.com
 *
 */

namespace App\Api\Services;


use App\Models\coupon\CmcPromotionCouponUser as CouponUser;

class Coupon
{
    /**
     * 获取优惠券列表
     * @param $id
     * @return array
     */
    public static function getUserCoupon($id)
    {
        if (empty($id)) return [];
        $data = CouponUser::getUserCoupon($id); // 调用模型关联查询
        $array = [];
        // 获取过期时间
        foreach ($data as $key => &$val){
            $startTime = $val['add_time'];
            $day = $val['coupon_time']; // 优惠券有效期（天）
            $endTime = strtotime($startTime) + $day * 24 *3600; //转换为时间戳（结束时间）
            // 获取过期时间
            $val['end_time'] = date("Y-m-d H:i:s",$endTime);
            if (time() > strtotime($val['end_time'])){
                $array[$key] = $val['cid'];
            }
        }
        // 根据优惠券id查看是否过期从而修改状态
        CouponUser::updateStatus($array);
        // 调用模型关联获取列表
        CouponUser::getUserCoupon($id);
        // 根据用户id查询不同的状态
        $used = self::time(CouponUser::getStatusUserCoupon($id,0));
        $unused = self::time(CouponUser::getStatusUserCoupon($id,1));
        $expired = self::time(CouponUser::getStatusUserCoupon($id,2));
        $data =[
            'unused'=>$used,
            'used'=>$unused,
            'have'=>$expired
        ];
        if (!$data)return [];
        return $data;
    }

    /**
     * 循环处理数组添加过期时间
     * @param $data
     * @return mixed
     */
    public static function time($data)
    {
        foreach ($data as $key => &$val) {
            $startTime = $val['add_time'];
            $days = $val['coupon_time'];
            $endTime = strtotime($startTime) + $days * 24 * 3600;//转为时间戳
            $val['end_time'] = date('Y-m-d H:i:s', $endTime);
        }
        return $data;
    }


}